package com.lepu.app.usercenter;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.app.application.MyApplication;
import com.app.utils.ObserverConst;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.usercenter.util.UserCenterUtil;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

public class UserBondActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, AsyncRequest, OnEditorActionListener {

	private static final String REQUEST_BOND = "request_bond";
	private static final String REQUEST_GET_CODE = "request_get_code";

	private static final int MSG_BOND_SUCCESS = 10;
	private static final int MSG_BOND_FAIL = 11;

	private static final int MSG_GET_CODE_SUCCESS = 20;
	private static final int MSG_GET_CODE_FAIL = 21;
	private static final int MSG_GET_CODE_UPDATE = 22;

	private Button mGetCodeButton;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.usercenter_bond_activity);

		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		// 移除更新验证码
		mHandler.removeMessages(MSG_GET_CODE_UPDATE);
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	private void init() {

		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("绑定手机");
		topbar.setonTopbarNewLeftLayoutListener(this);

		mGetCodeButton = (Button) findViewById(R.id.getCodeButton);
		TextView noCodeTextView = (TextView) findViewById(R.id.noCodeTextView);
		Button bondButton = (Button) findViewById(R.id.bondButton);

		mGetCodeButton.setTag(0);
		mGetCodeButton.setOnClickListener(mOnClickListener);
		noCodeTextView.setOnClickListener(mOnClickListener);
		bondButton.setOnClickListener(mOnClickListener);

		LinearLayout contentLayout = (LinearLayout) findViewById(R.id.contentLayout);
		contentLayout.setOnTouchListener(new View.OnTouchListener() {

			@SuppressLint("ClickableViewAccessibility")
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				UtilityBase.closeSoftInput(UserBondActivity.this);
				return false;
			}
		});

		EditText pwdEditText2 = (EditText) findViewById(R.id.pwdEditText2);
		pwdEditText2.setOnEditorActionListener(this);
	}

	private void requestGetCode() {
		EditText userEditText = (EditText) findViewById(R.id.userEditText);
		String userContent = userEditText.getText().toString().trim();

		boolean flag = UserCenterUtil.getBondCode(this, this,
				REQUEST_GET_CODE, userContent);
		if (flag) {
			showProgressDialog();
		}
	}

	private void requestBond() {
		EditText userEditText = (EditText) findViewById(R.id.userEditText);
		EditText codeEditText = (EditText) findViewById(R.id.codeEditText);
		EditText pwdEditText = (EditText) findViewById(R.id.pwdEditText);
		EditText pwdEditText2 = (EditText) findViewById(R.id.pwdEditText2);

		String userContent = userEditText.getText().toString().trim();
		String codeContent = codeEditText.getText().toString().trim();
		String pwdContent = pwdEditText.getText().toString().trim();
		String pwdContent2 = pwdEditText2.getText().toString().trim();

		boolean flag = UserCenterUtil.bond(this, this, REQUEST_BOND,
				userContent, codeContent, pwdContent, pwdContent2);
		if (flag) {
			showProgressDialog();
		}
	}

	private void checkCode() {

		EditText userEditText = (EditText) findViewById(R.id.userEditText);

		final String userContent = userEditText.getText().toString().trim();

		if (TextUtils.isEmpty(userContent) || userContent.length() != 11) {
			UIHelper.showToast(UserBondActivity.this,
					R.string.usercenter_user_msg);
			return;
		}

		new MyDialog(UserBondActivity.this)
				.setMessage(R.string.usercenter_code_message)
				.setNegativeButton(R.string.usercenter_code_go,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								requestGetCode();
							}
						})
				.setPositiveButton(R.string.usercenter_code_jump,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

								Intent intent = new Intent(
										UserBondActivity.this,
										RegisterByQuestionActivity.class);
								intent.putExtra("phone", userContent);
								startActivity(intent, true);
							}
						}).create(null).show();
	}

	View.OnClickListener mOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.getCodeButton:

				// int tag = (Integer) v.getTag();
				// if (tag == 0) {
				// requestGetCode();
				// } else {
				// checkCode();
				// }
				// 不需要跳过验证
				requestGetCode();
				break;
			case R.id.noCodeTextView:

				checkCode();
				break;
			case R.id.bondButton:

				requestBond();
				break;
			default:
				break;
			}
		}
	};

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_GET_CODE_UPDATE:

				int codeText = Integer.parseInt(mGetCodeButton.getText()
						.toString());
				codeText--;

				mGetCodeButton.setText(codeText + "");
				if (codeText <= 0) {
					mHandler.removeMessages(MSG_GET_CODE_UPDATE);
					mGetCodeButton.setTag(1);
					mGetCodeButton.setText("重新获取验证码");
					mGetCodeButton.setEnabled(true);
				} else {
					mHandler.sendEmptyMessageDelayed(MSG_GET_CODE_UPDATE, 1000);
				}

				break;
			case MSG_GET_CODE_SUCCESS:
				hideProgressDialog();

				mHandler.removeMessages(MSG_GET_CODE_UPDATE);
				mGetCodeButton.setTag(0);
				mGetCodeButton.setEnabled(false);
				mGetCodeButton.setText("60");
				mHandler.sendEmptyMessageDelayed(MSG_GET_CODE_UPDATE, 1000);
				break;
			case MSG_GET_CODE_FAIL:
				hideProgressDialog();
				
				int code = msg.arg1;
				if(code == 102)
				{
					UIHelper.showToast(UserBondActivity.this, "该手机号已绑定，请重新输入");
				}
				break;
			case MSG_BOND_SUCCESS:
				EditText userEditText = (EditText) findViewById(R.id.userEditText);
				String userContent = userEditText.getText().toString().trim();

				//更新绑定手机号
				LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
				loginInfo.MobilePhone = userContent;
				LoginInfo.saveLoginInfo(UserBondActivity.this,loginInfo);

				ObserverManager.getInstance().notify(
						ObserverConst.NOTIFY_MY_BOND_PHONE_CHANGE, null,
						userContent);

				hideProgressDialog();
				finish(true);

				break;
			case MSG_BOND_FAIL:
				hideProgressDialog();
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_GET_CODE)) {
			mHandler.sendEmptyMessage(MSG_GET_CODE_SUCCESS);
		} else if (object.equals(REQUEST_BOND)) {
			mHandler.sendEmptyMessage(MSG_BOND_SUCCESS);
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_GET_CODE)) {
			
			int code = 0;
			try {
				JSONObject jsonObject = new JSONObject(errorMessage);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				code = obj1.optInt("Status");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_GET_CODE_FAIL;
			msg.arg1 = code;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_BOND)) {
			mHandler.sendEmptyMessage(MSG_BOND_FAIL);
		}
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		switch (actionId) {
		case EditorInfo.IME_ACTION_DONE:

			requestBond();
			break;
		}
		return true;
	}

}
